package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/checkgroup")
@Slf4j
public class CheckGroupController {

	@Reference
	CheckGroupService checkGroupService;

	@RequestMapping("/add")
	public Result add(@RequestBody Map<String,Object> map){


		JSONObject jsonObject =(JSONObject) map.get("checkGroup");

		CheckGroup checkGroup = jsonObject.toJavaObject(CheckGroup.class);

		log.debug("checkGroup==="+checkGroup.toString());

		Object o = map.get("checkitemIds");

		JSONArray jsonArray = (JSONArray) o;

		Integer[] checkitemIds = jsonArray.toArray(new Integer[]{});

		log.debug("checkitemIds"+checkitemIds.toString());


		checkGroupService.add(checkGroup,checkitemIds);

		return new Result(true, MessageConst.ADD_CHECKGROUP_SUCCESS);
	}

	@RequestMapping("/findPage")
	public Result findPage(@RequestBody QueryPageBean queryPageBean){

		PageResult pageResult = checkGroupService.findPage(queryPageBean);

		return new Result(true, MessageConst.QUERY_CHECKITEM_SUCCESS,pageResult);
	}

	@RequestMapping("/delById")
	public Result delById(Integer id){

		checkGroupService.delById(id);

		log.debug("删除检查组成功  id="+id);

		return new Result(true,MessageConst.DELETE_CHECKGROUP_FAIL);
	}

	@RequestMapping("/findById")
	public Result findById(Integer id){

		CheckGroup checkGroup = checkGroupService.findById(id);


		return new Result(true,MessageConst.QUERY_CHECKGROUP_SUCCESS,checkGroup);
	}

	@RequestMapping("/findCheckItemIdsById")
	public Result findCheckItemIdsById(Integer id){

		Integer[] checkItemIds = checkGroupService.findCheckItemIdsById(id);

		return new Result(true,MessageConst.QUERY_CHECKGROUP_SUCCESS,checkItemIds);
	}


	@RequestMapping("/edit")
	public Result edit(@RequestBody CheckGroup checkGroup,Integer[] checkitemIds){

		checkGroupService.edit(checkGroup,checkitemIds);

		log.debug("编辑检查组成功");

		return new Result(true,MessageConst.EDIT_CHECKGROUP_SUCCESS);
	}

	@RequestMapping("/findAll")
	public Result findAll(){

		List<CheckGroup> checkGroupList = checkGroupService.findAll();

		System.out.println(checkGroupList.toString());
		log.debug("检查组查询所有成功");


		return new Result(true,MessageConst.QUERY_CHECKGROUP_SUCCESS,checkGroupList);
	}
}
